package utils

import (
	"github.com/kataras/iris/v12"
)

type Resp struct {
	statusCode int
	errCode    int64
	msg        interface{}
	data       interface{}
	debug      interface{}

	ctx    iris.Context
	isProd bool
}

const (
	ErrCodeOk = 0 // 没有错误
)

func NewResp(ctx iris.Context, isProd bool) (r *Resp) {
	r = &Resp{
		statusCode: iris.StatusOK,
		errCode:    ErrCodeOk,
	}
	r.isProd = isProd
	r.ctx = ctx
	return r
}

func (r *Resp) StatusCode(code int) *Resp {
	r.statusCode = code
	return r
}

func (r *Resp) ErrCode(errCode int64) *Resp {
	r.errCode = errCode
	return r
}
func (r *Resp) Data(data interface{}) *Resp {
	r.data = data
	return r
}

func (r *Resp) Msg(msg interface{}) *Resp {
	r.msg = msg
	return r
}

func (r *Resp) Debug(debugInfo interface{}) *Resp {
	if r.isProd {
		return r
	}
	r.debug = debugInfo
	return r
}

func (r *Resp) Echo() {
	ctx := r.ctx
	ctx.StatusCode(r.statusCode)

	if r.statusCode != iris.StatusOK &&
		r.statusCode != iris.StatusBadRequest {
		return
	}

	s := struct {
		ErrCode int64       `json:"errCode"`
		Data    interface{} `json:"data,omitempty"`
		Msg     interface{} `json:"msg,omitempty"`
		Debug   interface{} `json:"debug,omitempty"`
	}{
		ErrCode: r.errCode,
		Data:    r.data,
		Msg:     r.msg,
		Debug:   r.debug,
	}
	_, _ = ctx.JSON(s)
}

// 200
func (r *Resp) Ok() {
	r.StatusCode(iris.StatusOK).Echo()
}

// 400
func (r *Resp) Err(errMsg interface{}) {
	r.Msg(errMsg).StatusCode(iris.StatusBadRequest).Echo()
}
